/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.um.sso.othersystem;

import java.io.IOException;

import javax.servlet.http.Cookie;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.jinhe.tss.core.sso.Environment;
import com.jinhe.tss.core.sso.ILoginCustomizer;
import com.jinhe.tss.core.sso.IOperator;
import com.jinhe.tss.core.sso.IPWDOperator;
import com.jinhe.tss.core.sso.IdentityTranslator;
import com.jinhe.tss.core.sso.IdentityTranslatorFactory;
import com.jinhe.tss.core.sso.appserver.AppServer;
import com.jinhe.tss.core.sso.context.Context;
import com.jinhe.tss.core.util.XMLDocUtil;

/** 
 * <p> JCZLLoginCustomizer.java </p> 
 * 基于基础资料的金财工程项目单点登录实现类。
 * 
 * 将登陆用户转换为相应的JCZL资料用户，通过httpClient模拟客户端调用JCZL应用的登陆servlet login.in进行登陆。
 * 登陆成功后将返回的令牌（key）存放到当前的session以及cookie中，以后每次调用JCZL的页面将该令牌设置到请求的header中即可被JCZL的
 * AutoLoginFilter拦截到进行自动登陆。
 * 
 */
public class JCZLLoginCustomizer implements ILoginCustomizer {
    
    protected Logger log = Logger.getLogger(this.getClass());
    
    AppServer appServer = Context.getApplicationContext().getAppServer("JCZL");

    public void execute() {
        //将当前登陆的用户转换成JCZL应用的用户
        IdentityTranslator translator = IdentityTranslatorFactory.getTranslator();
        IOperator operator = translator.translate(Environment.getOperatorId(), appServer.getCode());
        
        String loginName = operator.getLoginName();
        IPWDOperator passwordOperator = (IPWDOperator) operator;
        String password = passwordOperator.getPassword();
        
        String key = loginJCZL(loginName, password);
        if(key != null){
            Context.getRequestContext().getSession().setAttribute("_key", key);
            Context.getResponse().addCookie(new Cookie("_key", key));
        }
    }

    public String loginJCZL(String loginName, String password){
        HttpClient httpClient = new HttpClient(); //构造HttpClient的实例
        
        PostMethod postMethod = new PostMethod(appServer.getBaseURL() + "/login.in");
        // 填入各个表单域的值
        NameValuePair[] params = { new NameValuePair("operatorCode", loginName), new NameValuePair("password", password) };
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(params);
        
        // 执行postMethod
        String key = null;
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            if(statusCode == HttpStatus.SC_OK){
                // 读取内容
                byte[] responseBody = postMethod.getResponseBody();
                key = XMLDocUtil.dataXml2Doc(new String(responseBody)).selectSingleNode("//key").getText();
            }
        } catch (HttpException e) {
            log.error("对基础资料进行单点登陆时，登陆servlet的连接地址可能有误！", e);
        } catch (IOException e) {
            log.error("对基础资料进行单点登陆时，出现IO异常！", e);
        }finally{
            postMethod.releaseConnection();
        }
        return key;
    }
}

